#include <iostream>
#include <string>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> //还有htons
#include <unistd.h>


void Usage(const std::string& proc) //使用手册
{
    std::cout << "/n/t. Usage: " << proc << " serve_ip serve_prot" << std::endl;
    std::cout << std::endl; 
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    
    //如果正确输入，那么开始通信
    //先提取，ip和port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //填写服务端字段
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    //server.sin_addr.s_addr = inet_addr(serverip.c_str()); //inet_addr有线程安全问题
    inet_aton(serverip.c_str(), &(server.sin_addr));
    socklen_t len = sizeof(server);

    //创建 socket fd
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socker error" << std::endl;
        return 1;
    }

    std::string message;
    char buffer[1024] = { 0 };
    
    while (true)
    {
        std::cout << "please enter@ "; 
        getline(std::cin, message); //获取信息 —> 阻塞等待输入

        //client需要bind吗？ —> 当然需要。只不过OS会在client向serve发送第一条信息的时候
        // OS会给随机bind一个唯一的端口号
        
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, len); //发送信息
        
        struct sockaddr_in temp; //接受
        socklen_t len = sizeof(temp);

        ssize_t ret_recv = recvfrom(sockfd, buffer, 1023, 0, (struct sockaddr*)&temp, &len); //接受回复信息
        if(ret_recv > 0)
        {
            buffer[ret_recv] = 0;
            std::cout << buffer << std::endl;
        }

    }
    
    close(sockfd);
    return 0;
}